import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import('@/views/layout'),
    redirect: '/home', // 默认显示首页的二级路由
    children: [
      {
        path: 'home',
        component: () => import('@/views/home')
      },
      {
        path: '/user-info',
        component: () => import('@/views/userinfo')
      },
      {
        path: 'user-avatar',
        component: () => import('@/views//useravatar')
      },
      {
        path: 'user-pwd',
        component: () => import('@/views/userpwd')
      },
      {
        path: 'art-cate',
        component: () => import('@/views/artcate')
      },
      {
        path: 'art-list',
        component: () => import('@/views/artlist')
      }

    ]
  },

  { path: '/register', component: () => import('@/views/register') },
  { path: '/login', component: () => import('@/views/Login') }
]

const router = new VueRouter({
  routes
})
// 创建登录与注册的登录路由
const whiteList = ['/login', '/register']
// 全局路由守卫
router.beforeEach((to, from, next) => {
  const token = store.state.token
  // 判断是否有登录
  if (token) {
    // 判断是否有用户信息
    // 没有就调用获取用户信息
    if (!store.state.userInfo.username) {
      store.dispatch('getUserINfoActions')
    }
    // 调用后放行
    next()
  } else {
    // 未登录
    // 跳转login
    // 对象方法判断是否有登录页面或注册页面
    // including方法对比是否有相同的value
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // 没有登录跳转到登录页面
      next('/login')
    }
  }
})

export default router
